<template>
  <div class="goods-form">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>{{ isEdit ? '编辑商品' : '添加商品' }}</span>
        </div>
      </template>

      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        class="form"
      >
        <!-- 基本信息 -->
        <el-divider>基本信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="商品名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入商品名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品分类" prop="categoryId">
              <el-select
                v-model="form.categoryId"
                placeholder="请选择商品分类"
                style="width: 100%"
              >
                <el-option
                  v-for="item in categories"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="所属商店" prop="shopId">
              <el-input-number
                v-model="form.shopId"
                :min="1"
                :precision="0"
                placeholder="请输入商店ID"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品价格" prop="price">
              <el-input-number
                v-model="form.price"
                :precision="2"
                :step="0.1"
                :min="0"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="品牌ID" prop="brandId">
              <el-input-number
                v-model="form.brandId"
                :min="0"
                :precision="0"
                placeholder="请输入品牌ID，如无可不填"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品库存" prop="stock">
              <el-input-number
                v-model="form.stock"
                :min="0"
                :precision="0"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 商品图片 -->
        <el-divider>商品图片</el-divider>
        <el-form-item label="主图" prop="image">
          <el-upload
            class="image-uploader"
            :action="null"
            :http-request="uploadMainImage"
            :show-file-list="false"
            :before-upload="beforeImageUpload"
          >
            <img v-if="form.image" :src="form.image" class="image" />
            <el-icon v-else class="image-uploader-icon"><Plus /></el-icon>
          </el-upload>
          <div class="image-tip">建议尺寸：800x800px，支持jpg、png格式</div>
        </el-form-item>

        <el-form-item label="商品图片" prop="images">
          <el-upload
            class="images-uploader"
            :action="null"
            :http-request="uploadGalleryImage"
            list-type="picture-card"
            :file-list="imageList"
            :before-upload="beforeImageUpload"
            :on-remove="handleImageRemove"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
          <div class="image-tip">最多上传9张图片，建议尺寸：800x800px</div>
        </el-form-item>

        <!-- 商品详情 -->
        <el-divider>商品详情</el-divider>
        <el-form-item label="商品描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="4"
            placeholder="请输入商品描述"
          />
        </el-form-item>

        <el-form-item label="商品详情" prop="detail">
          <el-input
            v-model="form.detail"
            type="textarea"
            :rows="6"
            placeholder="请输入商品详情"
          />
        </el-form-item>

        <!-- SKU管理 -->
        <el-divider>SKU管理</el-divider>
        
        <!-- 规格设置 -->
        <el-form-item label="规格设置">
          <div class="spec-container">
            <div v-for="(spec, index) in specs" :key="index" class="spec-item">
              <el-input
                v-model="spec.name"
                placeholder="规格名称"
                class="spec-name"
              />
              <el-tag
                v-for="(value, vIndex) in spec.values"
                :key="vIndex"
                closable
                @close="removeSpecValue(index, vIndex)"
                class="spec-value"
              >
                {{ value }}
              </el-tag>
              <div class="spec-value-input">
                <el-input
                  v-model="specValueInputs[index]"
                  placeholder="规格值"
                  @keyup.enter="addSpecValue(index)"
                />
                <el-button @click="addSpecValue(index)" :disabled="!specValueInputs[index]">
                  添加
                </el-button>
              </div>
              <el-button type="danger" @click="removeSpec(index)" circle>
                <el-icon><Delete /></el-icon>
              </el-button>
            </div>
            <el-button type="primary" @click="addSpec" plain>
              添加规格项
            </el-button>
          </div>
        </el-form-item>

        <!-- 规格模板预览 -->
        <el-form-item label="规格模板预览">
          <el-alert
            title="此数据将作为商品规格模板保存"
            type="info"
            :closable="false"
          />
          <el-input
            type="textarea"
            :rows="3"
            :value="getFormattedSpecTemplate()"
            readonly
          />
        </el-form-item>

        <!-- 生成SKU列表 -->
        <el-form-item>
          <el-button type="primary" @click="generateSkuList" :disabled="!canGenerateSkus">
            生成SKU列表
          </el-button>
        </el-form-item>

        <!-- SKU列表 -->
        <el-form-item v-if="form.skuList && form.skuList.length > 0">
          <el-table :data="form.skuList" border style="width: 100%">
            <el-table-column label="规格" min-width="200">
              <template #default="{ row }">
                <div class="sku-specs">
                  <el-tag v-for="(value, key) in getSpecsObject(row.specs)" :key="key" size="small">
                    {{ key }}: {{ value }}
                  </el-tag>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="价格" width="120">
              <template #default="{ row }">
                <el-input-number
                  v-model="row.price"
                  :precision="2"
                  :step="0.1"
                  :min="0"
                  controls-position="right"
                  style="width: 100px"
                />
              </template>
            </el-table-column>
            <el-table-column label="成本价" width="120">
              <template #default="{ row }">
                <el-input-number
                  v-model="row.costPrice"
                  :precision="2"
                  :step="0.1"
                  :min="0"
                  controls-position="right"
                  style="width: 100px"
                />
              </template>
            </el-table-column>
            <el-table-column label="库存" width="120">
              <template #default="{ row }">
                <el-input-number
                  v-model="row.stock"
                  :min="0"
                  :precision="0"
                  controls-position="right"
                  style="width: 100px"
                />
              </template>
            </el-table-column>
            <el-table-column label="库存预警" width="120">
              <template #default="{ row }">
                <el-input-number
                  v-model="row.stockThreshold"
                  :min="0"
                  :precision="0"
                  controls-position="right"
                  style="width: 100px"
                />
              </template>
            </el-table-column>
            <el-table-column label="图片" width="120">
              <template #default="{ row }">
                <el-upload
                  class="sku-image-uploader"
                  :action="null"
                  :http-request="(options) => uploadSkuImage(options, row)"
                  :show-file-list="false"
                  :before-upload="beforeImageUpload"
                >
                  <img v-if="row.mainImage" :src="row.mainImage" class="sku-image" />
                  <el-icon v-else class="sku-image-uploader-icon"><Plus /></el-icon>
                </el-upload>
              </template>
            </el-table-column>
            <el-table-column label="状态" width="100">
              <template #default="{ row }">
                <el-switch v-model="row.status" />
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>

        <!-- 其他设置 -->
        <el-divider>其他设置</el-divider>
        <el-form-item label="商品状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :value="1">上架</el-radio>
            <el-radio :value="0">下架</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 提交按钮 -->
        <el-form-item>
          <el-button type="primary" @click="handleSubmit" :loading="loading">
            保存
          </el-button>
          <el-button @click="handleCancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElLoading } from 'element-plus'
import { Plus, Delete } from '@element-plus/icons-vue'
import service from '@/utils/request'
import { getGoodsDetail, addGoods, updateSpu, getSkuList, addSku, updateSku } from '@/api/goods'
import { getSecondCategoryList } from '@/api/category'
import { useAdminStore } from '@/stores/modules/admin'

const route = useRoute()
const router = useRouter()
const formRef = ref(null)
const loading = ref(false)
const adminStore = useAdminStore()

// 是否为编辑模式
const isEdit = computed(() => !!route.params.id)

// 上传相关
const uploadUrl = import.meta.env.VITE_API_BASE_URL + '/files/jiang/upload'
const uploadHeaders = {
  Authorization: `Bearer ${adminStore.accessToken || localStorage.getItem('admin_token')}`
}

// 分类列表
const categories = ref([])

// 图片列表
const imageList = ref([])

// 表单数据
const form = ref({
  name: '',
  categoryId: '',
  shopId: 1, // 默认商店ID为1
  brandId: null, // 品牌ID，可为空
  price: 0,
  stock: 0,
  image: '',
  images: [],
  description: '',
  detail: '',
  status: 1,
  spuCode: '',
  title: '',
  skuList: []
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入商品名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  categoryId: [
    { required: true, message: '请选择商品分类', trigger: 'change' }
  ],
  shopId: [
    { required: true, message: '请输入商店ID', trigger: 'blur' }
  ],
  price: [
    { required: true, message: '请输入商品价格', trigger: 'blur' }
  ],
  stock: [
    { required: true, message: '请输入商品库存', trigger: 'blur' }
  ],
  image: [
    { required: true, message: '请上传商品主图', trigger: 'change' }
  ],
  description: [
    { required: true, message: '请输入商品描述', trigger: 'blur' }
  ]
}

// SKU规格管理
const specs = ref([])
const specValueInputs = ref([])

// 添加规格项
const addSpec = () => {
  specs.value.push({
    name: '',
    values: []
  })
  specValueInputs.value.push('')
}

// 移除规格项
const removeSpec = (index) => {
  specs.value.splice(index, 1)
  specValueInputs.value.splice(index, 1)
}

// 添加规格值
const addSpecValue = (index) => {
  const value = specValueInputs.value[index].trim()
  if (value && !specs.value[index].values.includes(value)) {
    specs.value[index].values.push(value)
    specValueInputs.value[index] = ''
  }
}

// 移除规格值
const removeSpecValue = (specIndex, valueIndex) => {
  specs.value[specIndex].values.splice(valueIndex, 1)
}

// 是否可以生成SKU列表
const canGenerateSkus = computed(() => {
  return specs.value.length > 0 && 
    specs.value.every(spec => spec.name && spec.values.length > 0)
})

// 生成SKU列表
const generateSkuList = () => {
  // 检查规格设置是否有效
  if (!canGenerateSkus.value) {
    ElMessage.warning('请先设置有效的规格项和规格值')
    return
  }
  
  // 生成规格组合
  const combinations = generateSpecCombinations(specs.value)
  
  // 创建SKU列表
  const defaultPrice = form.value.price || 0
  const defaultCostPrice = defaultPrice * 0.8 // 默认成本价为售价的80%
  const defaultStock = 100
  const defaultThreshold = 10
  
  // 使用spuCode作为SKU编码前缀
  const spuCode = form.value.spuCode || `SPU${Date.now()}`
  
  // 生成新的SKU列表
  form.value.skuList = combinations.map((combo, index) => {
    // 检查是否已存在相同规格的SKU
    const existingSku = form.value.skuList?.find(sku => {
      const skuSpecs = typeof sku.specs === 'string' ? JSON.parse(sku.specs) : sku.specs
      const isEqual = Object.keys(combo).every(key => skuSpecs[key] === combo[key])
      return isEqual
    })
    
    if (existingSku) {
      return existingSku
    }
    
    // 生成SKU编码
    const skuCode = generateSkuCode(spuCode, combo)
    
    // 创建新的SKU
    return {
      id: null, // 新SKU没有ID
      skuCode,
      spuId: isEdit.value ? parseInt(route.params.id) : null,
      specs: JSON.stringify(combo),
      price: defaultPrice,
      costPrice: defaultCostPrice,
      stock: defaultStock,
      stockThreshold: defaultThreshold,
      weight: 0.2,
      volume: 0.01,
      mainImage: form.value.image, // 默认使用SPU主图
      status: true
    }
  })
  
  ElMessage.success(`已生成 ${form.value.skuList.length} 个SKU`)
}

// 生成规格组合
const generateSpecCombinations = (specs) => {
  // 如果没有规格，返回空数组
  if (!specs.length) return []
  
  // 递归生成所有组合
  const combine = (index, current) => {
    // 如果已经处理完所有规格，返回当前组合
    if (index === specs.length) {
      return [current]
    }
    
    const spec = specs[index]
    const results = []
    
    // 为当前规格的每个值生成组合
    for (const value of spec.values) {
      const newCurrent = { ...current, [spec.name]: value }
      const subResults = combine(index + 1, newCurrent)
      results.push(...subResults)
    }
    
    return results
  }
  
  return combine(0, {})
}

// 生成SKU编码
const generateSkuCode = (spuCode, specs) => {
  // 将规格值转换为编码后缀
  const suffix = Object.values(specs)
    .map(value => value.substring(0, 1).toUpperCase()) // 取每个值的首字母
    .join('')
  
  return `${spuCode}#${suffix}`
}

// 解析规格JSON字符串为对象
const getSpecsObject = (specs) => {
  if (!specs) return {}
  
  try {
    return typeof specs === 'string' ? JSON.parse(specs) : specs
  } catch (e) {
    console.error('解析规格失败:', e)
    return {}
  }
}

// 上传SKU图片
const uploadSkuImage = async (options, sku) => {
  const { file } = options
  try {
    // 显示加载状态
    const loadingInstance = ElLoading.service({
      text: '图片上传中...',
      background: 'rgba(0, 0, 0, 0.7)'
    })
    
    // 使用Promise包装XMLHttpRequest
    const response = await new Promise((resolve, reject) => {
      const formData = new FormData()
      formData.append('file', file)
      
      const xhr = new XMLHttpRequest()
      // 使用管理员上传接口
      xhr.open('POST', import.meta.env.VITE_API_BASE_URL + '/files/jiang/upload', true)
      
      // 使用管理员token
      if (adminStore.accessToken) {
        xhr.setRequestHeader('Authorization', `Bearer ${adminStore.accessToken}`)
      } else {
        // 如果没有管理员token，尝试从localStorage获取
        const token = localStorage.getItem('admin_token')
        if (token) {
          xhr.setRequestHeader('Authorization', `Bearer ${token}`)
        }
      }
      
      xhr.onload = function() {
        if (xhr.status >= 200 && xhr.status < 300) {
          try {
            const response = JSON.parse(xhr.responseText)
            resolve(response.data)
          } catch (e) {
            resolve(xhr.responseText)
          }
        } else {
          reject(new Error(`上传失败：${xhr.status} ${xhr.statusText}`))
        }
      }
      
      xhr.onerror = function() {
        reject(new Error('网络错误，上传失败'))
      }
      
      xhr.send(formData)
    })
    
    // 关闭加载状态
    loadingInstance.close()
    
    // 处理响应
    let imageUrl = ''
    
    if (response && typeof response === 'string') {
      imageUrl = response
    } else if (response && response.data) {
      imageUrl = typeof response.data === 'string' ? response.data : response.data.url || response.data
    } else {
      imageUrl = response
    }
    
    // 检查URL是否有效
    if (!imageUrl) {
      throw new Error('上传成功但未获取到有效的图片URL')
    }
    
    // 更新SKU图片
    sku.mainImage = imageUrl
    
    ElMessage.success('SKU图片上传成功')
  } catch (error) {
    // 关闭可能存在的加载状态
    try {
      ElLoading.service().close()
    } catch (e) {
      // 忽略关闭加载状态时的错误
    }
    
    console.error('SKU图片上传失败:', error)
    ElMessage.error(error.message || '上传失败，请重试')
  }
}

// 加载商品详情时解析SKU规格
const parseSkuSpecs = (skuList) => {
  if (!skuList || skuList.length === 0) return
  
  // 收集所有规格项和规格值
  const specMap = {}
  
  skuList.forEach(sku => {
    try {
      const specsObj = typeof sku.specs === 'string' ? JSON.parse(sku.specs) : sku.specs
      
      Object.entries(specsObj).forEach(([key, value]) => {
        if (!specMap[key]) {
          specMap[key] = new Set()
        }
        specMap[key].add(value)
      })
    } catch (e) {
      console.error('解析SKU规格失败:', e)
    }
  })
  
  // 转换为specs数组格式
  specs.value = Object.entries(specMap).map(([name, valuesSet]) => ({
    name,
    values: Array.from(valuesSet)
  }))
  
  // 初始化specValueInputs
  specValueInputs.value = specs.value.map(() => '')
}

// 加载分类列表
const loadCategories = async () => {
  try {
    // 使用二级分类API接口获取分类列表
    const data = await getSecondCategoryList()
    categories.value = data
  } catch (error) {
    console.error('加载分类列表失败：', error)
    ElMessage.error('加载分类列表失败')
  }
}

// 加载商品详情
const loadGoodsDetail = async () => {
  if (!isEdit.value) return
  
  loading.value = true
  try {
    // 使用API接口获取商品详情
    const data = await getGoodsDetail(route.params.id)
    console.log('获取到的商品详情:', data)
    
    // 填充表单数据，根据后端返回的字段进行适配
    form.value = {
      id: data.id,
      name: data.title,
      title: data.title,
      categoryId: data.categoryId,
      shopId: data.shopId,
      brandId: data.brandId,
      price: data.price,
      stock: calculateTotalStock(data.skuList),
      image: data.mainImage,
      images: data.subImages ? data.subImages.split(',') : [],
      description: data.description,
      detail: data.detailsHtml || '',
      status: data.status === null ? 1 : data.status,
      spuCode: data.spuCode,
      skuList: data.skuList || []
    }
    
    // 处理图片列表
    if (data.subImages) {
      const imageUrls = data.subImages.split(',')
      imageList.value = imageUrls.map(url => ({
        url,
        name: url.split('/').pop()
      }))
    } else {
      imageList.value = []
    }
    
    // 解析规格模板
    if (data.specTemplate) {
      try {
        const template = JSON.parse(data.specTemplate)
        if (template.specs && Array.isArray(template.specs)) {
          // 转换为内部使用的格式
          specs.value = template.specs.map(spec => ({
            name: spec.key,
            values: spec.values || []
          }))
        }
      } catch (e) {
        console.error('解析规格模板失败:', e)
      }
    }
    
    // 解析SKU规格
    parseSkuSpecs(data.skuList)
    
  } catch (error) {
    console.error('加载商品详情失败：', error)
    ElMessage.error('加载商品详情失败')
  } finally {
    loading.value = false
  }
}

// 计算总库存
const calculateTotalStock = (skuList) => {
  if (!skuList || skuList.length === 0) return 0
  return skuList.reduce((total, sku) => total + sku.stock, 0)
}

// 图片上传前的验证
const beforeImageUpload = (file) => {
  const isImage = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传JPG/PNG格式的图片！')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过2MB！')
    return false
  }
  return true
}

// 上传主图
const uploadMainImage = async (options) => {
  const { file } = options
  try {
    // 显示加载状态
    const loadingInstance = ElLoading.service({
      text: '图片上传中...',
      background: 'rgba(0, 0, 0, 0.7)'
    })
    
    // 使用Promise包装XMLHttpRequest
    const response = await new Promise((resolve, reject) => {
      const formData = new FormData()
      formData.append('file', file)
      
      const xhr = new XMLHttpRequest()
      // 使用管理员上传接口
      xhr.open('POST', import.meta.env.VITE_API_BASE_URL + '/files/jiang/upload', true)
      
      // 使用管理员token
      if (adminStore.accessToken) {
        xhr.setRequestHeader('Authorization', `Bearer ${adminStore.accessToken}`)
      } else {
        // 如果没有管理员token，尝试从localStorage获取
        const token = localStorage.getItem('admin_token')
        if (token) {
          xhr.setRequestHeader('Authorization', `Bearer ${token}`)
        }
      }
      
      xhr.onload = function() {
        if (xhr.status >= 200 && xhr.status < 300) {
          try {
            const response = JSON.parse(xhr.responseText)
            resolve(response.data)
          } catch (e) {
            resolve(xhr.responseText)
          }
        } else {
          reject(new Error(`上传失败：${xhr.status} ${xhr.statusText}`))
        }
      }
      
      xhr.onerror = function() {
        reject(new Error('网络错误，上传失败'))
      }
      
      xhr.send(formData)
    })
    
    // 关闭加载状态
    loadingInstance.close()
    
    // 处理响应
    let imageUrl = ''
    
    if (response && typeof response === 'string') {
      imageUrl = response
    } else if (response && response.data) {
      imageUrl = typeof response.data === 'string' ? response.data : response.data.url || response.data
    } else {
      imageUrl = response
    }
    
    // 检查URL是否有效
    if (!imageUrl) {
      throw new Error('上传成功但未获取到有效的图片URL')
    }
    
    // 更新主图URL
    form.value.image = imageUrl
    
    ElMessage.success('主图上传成功')
  } catch (error) {
    // 关闭可能存在的加载状态
    try {
      ElLoading.service().close()
    } catch (e) {
      // 忽略关闭加载状态时的错误
    }
    
    console.error('主图上传失败:', error)
    ElMessage.error(error.message || '上传失败，请重试')
  }
}

// 上传商品图片
const uploadGalleryImage = async (options) => {
  const { file } = options
  try {
    // 显示加载状态
    const loadingInstance = ElLoading.service({
      text: '图片上传中...',
      background: 'rgba(0, 0, 0, 0.7)'
    })
    
    // 使用Promise包装XMLHttpRequest
    const response = await new Promise((resolve, reject) => {
      const formData = new FormData()
      formData.append('file', file)
      
      const xhr = new XMLHttpRequest()
      // 使用管理员上传接口
      xhr.open('POST', import.meta.env.VITE_API_BASE_URL + '/files/jiang/upload', true)
      
      // 使用管理员token
      if (adminStore.accessToken) {
        xhr.setRequestHeader('Authorization', `Bearer ${adminStore.accessToken}`)
      } else {
        // 如果没有管理员token，尝试从localStorage获取
        const token = localStorage.getItem('admin_token')
        if (token) {
          xhr.setRequestHeader('Authorization', `Bearer ${token}`)
        }
      }
      
      xhr.onload = function() {
        if (xhr.status >= 200 && xhr.status < 300) {
          try {
            const response = JSON.parse(xhr.responseText)
            resolve(response.data)
          } catch (e) {
            resolve(xhr.responseText)
          }
        } else {
          reject(new Error(`上传失败：${xhr.status} ${xhr.statusText}`))
        }
      }
      
      xhr.onerror = function() {
        reject(new Error('网络错误，上传失败'))
      }
      
      xhr.send(formData)
    })
    
    // 关闭加载状态
    loadingInstance.close()
    
    // 处理响应
    let imageUrl = ''
    
    if (response && typeof response === 'string') {
      imageUrl = response
    } else if (response && response.data) {
      imageUrl = typeof response.data === 'string' ? response.data : response.data.url || response.data
    } else {
      imageUrl = response
    }
    
    // 检查URL是否有效
    if (!imageUrl) {
      throw new Error('上传成功但未获取到有效的图片URL')
    }
    
    // 添加到商品图片列表
    form.value.images.push(imageUrl)
    
    // 更新显示列表
    imageList.value.push({
      url: imageUrl,
      name: imageUrl.split('/').pop()
    })
    
    ElMessage.success('商品图片上传成功')
  } catch (error) {
    // 关闭可能存在的加载状态
    try {
      ElLoading.service().close()
    } catch (e) {
      // 忽略关闭加载状态时的错误
    }
    
    console.error('商品图片上传失败:', error)
    ElMessage.error(error.message || '上传失败，请重试')
  }
}

// 删除图片
const handleImageRemove = (file) => {
  const index = form.value.images.indexOf(file.url)
  if (index > -1) {
    form.value.images.splice(index, 1)
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    loading.value = true
    
    // 准备提交的数据，适配后端API格式
    const submitData = {
      spu: {
        ...(isEdit.value ? { id: parseInt(route.params.id) } : {}),
        spuCode: form.value.spuCode || generateSpuCode(),
        shopId: form.value.shopId || (adminStore.adminInfo?.shopId || 1),
        categoryId: form.value.categoryId,
        brandId: form.value.brandId || null,
        price: form.value.price,
        title: form.value.name, // 使用name作为title
        mainImage: form.value.image, // 使用image作为mainImage
        subImages: form.value.images.join(','), // 将images数组转为逗号分隔的字符串
        description: form.value.description,
        detailHtml: form.value.detail, // 使用detail作为detailHtml
        specTemplate: getSpecTemplateString(), // 将规格模板转为JSON字符串
        status: form.value.status === 1, // 将数字转换为布尔值，1为true，0为false
        isDeleted: false // 添加软删除标记
      },
      // 处理SKU列表，确保每个SKU都有正确的格式
      skuList: form.value.skuList.map(sku => ({
        ...sku,
        ...(isEdit.value ? { spuId: parseInt(route.params.id) } : {}),
        // 移除非编辑模式下的id字段
        ...(isEdit.value ? {} : { id: undefined }),
        // 确保有skuCode
        skuCode: sku.skuCode || `SKU${Date.now()}${Math.floor(Math.random() * 1000)}`,
        // 确保specs是字符串格式
        specs: typeof sku.specs === 'string' ? sku.specs : JSON.stringify(sku.specs),
        // 确保有价格字段
        price: sku.price || form.value.price,
        // 确保有成本价字段
        costPrice: sku.costPrice || (form.value.price * 0.8),
        // 确保有库存字段
        stock: sku.stock || 100,
        // 确保有库存预警值字段
        stockThreshold: sku.stockThreshold || 10,
        // 确保有重量字段
        weight: sku.weight || 0.2,
        // 确保有体积字段
        volume: sku.volume || 0.01,
        // 确保有主图字段
        mainImage: sku.mainImage || form.value.image,
        // 确保status是布尔值
        status: !!sku.status
      }))
    }
    
    console.log('提交的商品数据:', submitData)
    console.log('规格模板:', submitData.spu.specTemplate)
    console.log('模拟SQL插入语句: INSERT INTO spu (spu_code, shop_id, category_id, brand_id, price, title, main_image, sub_images, description, detail_html, spec_template, status, is_deleted) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)')
    
    if (isEdit.value) {
      // 使用updateSpu API
      await updateSpu(submitData)
      ElMessage.success('更新成功')
    } else {
      // 使用addGoods API
      await addGoods(submitData)
      ElMessage.success('添加成功')
    }
    
    router.push('/jiang/goods')
  } catch (error) {
    if (error === 'cancel') return
    console.error('保存失败：', error)
    ElMessage.error('保存失败，请重试')
  } finally {
    loading.value = false
  }
}

// 生成SPU编码
const generateSpuCode = () => {
  const now = new Date()
  const year = now.getFullYear().toString().slice(-2)
  const month = (now.getMonth() + 1).toString().padStart(2, '0')
  const day = now.getDate().toString().padStart(2, '0')
  const random = Math.floor(Math.random() * 10000).toString().padStart(4, '0')
  
  return `SPU${year}${month}${day}${random}`
}

// 取消
const handleCancel = () => {
  router.back()
}

// 初始化
onMounted(() => {
  loadCategories()
  loadGoodsDetail()
  
  // 设置默认shopId
  if (!form.value.shopId && adminStore.adminInfo?.shopId) {
    form.value.shopId = adminStore.adminInfo.shopId
  }
  
  // 如果是新增商品，添加一个默认规格项
  if (!isEdit.value) {
    addSpec()
  }
})

// 获取格式化的规格模板
const getFormattedSpecTemplate = () => {
  // 转换为指定格式 {"specs": [{"key": "规格名", "values": ["值1", "值2"]}]}
  const formattedSpecs = specs.value.map(spec => ({
    key: spec.name,
    values: spec.values
  }))
  
  return JSON.stringify({ specs: formattedSpecs }, null, 2)
}

// 获取规格模板JSON字符串
const getSpecTemplateString = () => {
  const formattedSpecs = specs.value.map(spec => ({
    key: spec.name,
    values: spec.values
  }))
  
  return JSON.stringify({ specs: formattedSpecs })
}
</script>

<style lang="scss" scoped>
.goods-form {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .form {
    max-width: 1000px;
    margin: 0 auto;
  }

  .image-uploader {
    :deep(.el-upload) {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);

      &:hover {
        border-color: var(--el-color-primary);
      }
    }

    .image-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 100px;
      height: 100px;
      text-align: center;
      line-height: 100px;
    }

    .image {
      width: 100px;
      height: 100px;
      display: block;
      object-fit: cover;
    }
  }

  .images-uploader {
    :deep(.el-upload--picture-card) {
      width: 100px;
      height: 100px;
      line-height: 100px;
    }
  }

  .image-tip {
    font-size: 12px;
    color: #909399;
    margin-top: 8px;
  }

  :deep(.el-divider__text) {
    font-size: 16px;
    font-weight: bold;
  }

  .spec-container {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;

    .spec-item {
      display: flex;
      align-items: center;
      gap: 10px;

      .spec-name {
        width: 100px;
      }

      .spec-value {
        margin-right: 10px;
      }

      .spec-value-input {
        display: flex;
        align-items: center;
        gap: 10px;
      }
    }
  }

  .sku-specs {
    display: flex;
    flex-wrap: wrap;
    gap: 5px;
  }

  .sku-image-uploader {
    :deep(.el-upload) {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);

      &:hover {
        border-color: var(--el-color-primary);
      }
    }

    .sku-image-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 100px;
      height: 100px;
      text-align: center;
      line-height: 100px;
    }

    .sku-image {
      width: 100px;
      height: 100px;
      display: block;
      object-fit: cover;
    }
  }
}
</style>
